package p.sglmsn.top.ext.wx.wxext.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.experimental.Accessors;
import p.sglmsn.top.ext.wx.controller.ReceiveNewsController;

import java.util.Optional;

@Data
@Accessors(chain = true)
public class SendDto {

    /**
     * 方法
     */
    protected String method;
    protected Integer[] type;
    protected String url;
    protected String name;
    protected String action;

    /**
     * pid
     */
    protected Integer pid;
    protected String myid;

    protected String msg;

    protected String wxid;
    /**
     * img  图片绝对路径
     */
    protected String img;
    /**
     * img类型  file
     */
    protected String imgType;
    /**
     * transferid   交易id
     */
    protected String transferid;
    protected String data;
    protected String token;


    /**
     * 微信启动路径
     */
    protected String path;
    protected String encryptusername;
    protected String ticket;
    protected Integer scene;


    public SendDto() {
        initPid(this);
    }


    public SendDto(String method, Integer pid) {
        this();
        this.method = method;
        this.pid = pid;
    }

    public SendDto(String method) {
        this.method = method;
    }

    public static SendDto create(Integer pid) {
        return new SendDto().setPid(pid);
    }

    public static SendDto create(Integer pid, String method) {
        return new SendDto().setPid(pid).setMethod(method);
    }

    public static SendDto create(String method) {
        SendDto sendDto = new SendDto(method).setPid(0);
        initPid(sendDto);
        return sendDto;
    }

    public static SendDto createMsg(String msg) {
        SendDto sendDto = new SendDto().setMsg(msg).setPid(0);
        initPid(sendDto);
        return sendDto;
    }

    public static String getFromWxId() {
        return new SendDto().wxid;
    }


    private static void initPid(SendDto sendDto) {
        JSONObject value = ReceiveNewsController.THREAD_LOCAL.get();
        Optional.ofNullable(value).ifPresent(jsonObject -> {
            Optional.ofNullable(jsonObject.getInteger("pid")).ifPresent(integer -> sendDto.setPid(integer));
            sendDto.setMyid(jsonObject.getString("myid"));
            Optional.ofNullable(jsonObject.getJSONObject("data")).ifPresent(t -> {
                Optional.ofNullable(t.getString("fromid")).ifPresent(s -> {
                    sendDto.setWxid(s);
                });
            });

        });
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }


}
